<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" size="small" @click="showCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table class="tree-table" :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index border>
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-error" style="color: red" v-if="scope.row.cat_deleted"></i>
          <i class="el-icon-success" style="color: lightgreen" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="edit" slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.cat_id)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeCateById(scope.row.cat_id)"></el-button>
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="30%" :close-on-click-modal="false" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="分类图片" prop="image">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleSuccess' :on-remove="handleRemove"  :file-list="fileList" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>         -->
        <el-form-item label="分类选择">
          <el-cascader v-model="selectedKeys" :options="ParentCateList" :props="cascadeProps" @change="handleChange" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="分类图片">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleEditSuccess' :on-remove="handleEditRemove" :file-list="fileList" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>         -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="80%" :close-on-click-modal="false">
      <img :src="previewPath" class="preview-img" />
    </el-dialog>

  </div>
</template>

<script>
import { basePath,uploadPath } from '../../../.env.development'

export default {
  created() {
    // this.getCateList()
    this.getCateList()
  },
  data() {
    return {
      basePath,
      uploadPath,
      addDialogVisible: false,
      editDialogVisible: false,
      previewVisible: false,
      previewPath: '',
      fileList: [],
      headerObj: {
        Authorization: JSON.parse(sessionStorage.getItem('userInfo')).token,
      },        
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [],
      ParentCateList: [],
      total: 0,
      selectedKeys: [],
      cascadeProps: {
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover',
        checkStrictly: true,
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'edit',
        },
      ],
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
        // image: []
      },
      editForm: {},
      addFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
      },
      editFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
      },
    }
  },
  methods: {
    // async getCateList() {
    //   const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
    //   console.log('分类 res', res)
    //   // if (res.meta.status !== 200) {
    //   //   return this.$message.error('获取商品分类失败')
    //   // }
    //   this.cateList = JSON.parse(res.data)
    //   this.total = res.total
    //   console.log(res.data)
    // },
    async getCateList() {
      console.log('uploadPath', basePath)
      const { data: res } = await this.$http.get('cate_display/')
      // if (res.meta.status !== 200) {
      //   return this.$message.error(res.meta.msg)
      // }
      this.cateList = res.data
      this.total = res.total
      console.log('cate_display res', res.data)
      // this.$message.success('获取角色成功')
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('cate_display/', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级商品分类数据失败')
      }
      this.ParentCateList = res.data
      console.log(res.data)
    },
    async addCate() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        this.fileList = []
        const { data: res } = await this.$http.post('categories/', this.addForm)
        // if (res.meta.status !== 201) {
        //   return this.$message.error('创建商品分类失败')
        // }
        console.log('addRoles res', res)
        if(res === '没有权限'){
          return this.$message.warning(res)
        }  
        this.addDialogVisible = false
        this.getCateList()
        this.$message.success('创建商品分类成功')
      })
    },
    showCateDialog() {
      this.addDialogVisible = true
      this.getParentCateList()
    },
    handlePreview(file) {
      this.previewVisible = true
      this.previewPath = file.url
      console.log('handlePreview file', file)
    },
    handleSuccess(response) {
      this.addForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleSuccess pics', this.addForm)
    },
    handleRemove(file) {
      const filePath = file.response.data.temp_path
      const i = this.addForm.image.findIndex(item => item.pic === filePath)
      console.log('handleRemove i',i)
      this.addForm.image.splice(i,1)
       console.log('handleRemove image',this.addForm.image)
    },
    handleEditSuccess(response) {
      this.editForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleEditSuccess pics', this.editForm)
    },
    handleEditRemove(file) {
      const filePath = file.temp_path || file.response.data.temp_path
      const i = this.editForm.image.findIndex(item => item.pic === filePath)
      console.log('handleEditRemove i',i)
      this.editForm.image.splice(i,1)
       console.log('handleEditRemove image',this.editForm.image)
    },
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getCateList()
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getCateList()
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    async showEditDialog(cateId) {
      const { data: res } = await this.$http.get(`categories/${cateId}`)
      console.log('showEditDialog', res)
      if (res === '没有权限') {
        return this.$message.error('查询商品分类信息失败')
      }
      if(res.image){
        res.image.forEach(item => {
        this.fileList.push({
          name: item.pic_id,
          url: basePath + item.pic,
          temp_path: item.pic
          })
          
        }) 
      }     
      this.editForm = res

      this.editDialogVisible = true
    },
    editDialogClose() {
      this.fileList = []
      this.$refs.editFormRef.resetFields()
    },
    editCate() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}/`, {
          cat_name: this.editForm.cat_name,
          // image: this.editForm.image
        })
        // if (res.meta.status !== 200) {
        //   return this.$message.error('修改分类失败')
        // }
        if (res === '没有权限') {
          return this.$message.error('查询商品分类信息失败')
        }        
        this.editDialogVisible = false
        this.getCateList()
        this.$message.success('修改分类成功')
      })
    },
    handleChange() {
      if (this.selectedKeys.length > 0) {
        console.log('handleChange', this.selectedKeys)
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addForm.cat_level = this.selectedKeys.length
      } else {
        console.log('handleChange cat_pid', this.addForm.cat_pid)
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    async removeCateById(cateId) {
      this.$confirm('确定要删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${cateId}`)
        // if (res.meta.status !== 200)   {
        //   return this.$message.error('删除分类失败')
        // }
        if(res === '没有权限'){
          return this.$message.warning(res)
        }          
        this.getCateList()
        this.$message.success('删除分类成功')
      })
    },
  },
}
</script>
<style lang="less" scoped>
.tree-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>